package com.shuqi.model.manager;

import java.util.ArrayList;
import java.util.List;

import android.text.TextUtils;

import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.Config;
import com.shuqi.common.DownLoadBookUtil;
import com.shuqi.common.DownLoadBookUtil.DeleteListener;
import com.shuqi.common.MyTask;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.download.core.DownloadManager;
import com.shuqi.download.database.DownloadInfo;
import com.shuqi.download.database.DownloadInfoDao;
import com.shuqi.download.listener.DownloadStateListener;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.VerifyBookDownLoadUrlModel;
import com.shuqi.model.bean.BookData;
import com.shuqi.model.bean.VerifyBookDownUrlInfo;
import com.shuqi.model.manager.BookCatalogManager.DownLoadListener;

public class DownLoadShuqiBook {
    private final String logTag = "DownLoadShuqiBook";

    private static DownLoadShuqiBook mDownLoadShuqiBook;

    private DownLoadShuqiBook() {}

    public static DownLoadShuqiBook getInstace() {
        if (mDownLoadShuqiBook == null) {
            mDownLoadShuqiBook = new DownLoadShuqiBook();
        }
        return mDownLoadShuqiBook;
    }

    /**
     * 注册下载监听
     * @param loadListener
     */
    public void registerDownStateListener(DownloadStateListener listener) {
        DownloadManager.getInstance().registerDownStateListener(listener);
    }
    /**
     * 解除注册下载监听
     * @param loadListener
     */
    public void unRegisterDownStateListener(DownloadStateListener listener) {
        DownloadManager.getInstance().unRegisterDownStateListener(listener);
    }

    /***下载全本书籍
     * @param userId
     * @param bookId
     */
    public synchronized void startDownBook(String userId, String bookId, StartDownBookListener startDownBookListener) {
        Log4an.i(logTag, "startDownBook() userId=" + userId + " bookId=" + bookId);
        startDownBook(userId, bookId, null,startDownBookListener);
    }

    public synchronized void startDownBook(String userId, String bookId, final String firstChapterId, final StartDownBookListener startDownBookListener) {
        Log4an.i(logTag, "startDownBook() userId=" + userId + " bookId=" + bookId
                + " firstChapterId=" + firstChapterId);
        DownloadManager.getInstance().add(userId, bookId);
        saveBookMark(bookId, userId, firstChapterId);
        // 1，检查书籍目录
        CheckBookCatalogListener listener = new CheckBookCatalogListener() {
            @Override
            public void onFinish(boolean isSuccess, final String userId, final String bookId) {
                Log4an.e(logTag, "checkBookCatalog isSuccess=" + isSuccess);
                if (isSuccess) {
                    // 2，校验下载地址
                    CheckBookDownUrlListener urlListener = new CheckBookDownUrlListener() {
                        @Override
                        public void onFinish(boolean isSuccess, VerifyBookDownUrlInfo info) {
                            Log4an.e(logTag, "checkBookDownLoadUrl isSuccess=" + isSuccess);
                            if (isSuccess) {
                                //3,开始下载
                                Log4an.e(logTag, "开始下载 userId=" + userId + " bookId=" + bookId
                                        + " url=" + info.getDownLoadUrl());
                                DownloadManager.getInstance().exec(userId, bookId, info.getDownLoadUrl(),info.getThreadCount());
                                startDownBookListener.onFinish(true, "下载任务添加成功");
                                //添加书签
                            }else{
                                DownloadManager.getInstance().remove(userId, bookId);
                                startDownBookListener.onFinish(false, info==null?getVerifyDownUrlErrorTips():info.getMessage());
                            }
                        }
                    };
                    checkBookDownLoadUrl(userId, bookId, urlListener);
                }else{
                    DownloadManager.getInstance().remove(userId, bookId);
                    startDownBookListener.onFinish(false, getCatalogErrorTips());
                }
            }
        };
        checkBookCatalog(userId, bookId, listener);
    }

    /***
     * 暂停下载
     * @param userId
     * @param bookId
     */
    public void stopDownBook(String userId, String bookId) {
        DownloadManager.getInstance().stop(userId, bookId);
    }
    /***
     * 暂停所有下载
     * @param userId
     * @param bookId
     */
    public void stopAllDownBook(String userId) {
        DownloadManager.getInstance().stopAll();
    }
    /***
     * 清理缓存
     * @param userId
     * @param bookId
     */
    public void clearAllCache() {
        DownloadInfoDao.getInstance().clear();
    }

    /***
     * 删除下载任务
     * @param userId
     * @param bookId
     */
    public void deleteDownBookTask(String userId, String bookId){
        deleteDownBookTask(userId, bookId, null,false);
    }
    /***
     * 删除下载任务
     * @param userId
     * @param bookId
     * @param listener
     * @param isDeleteBookData 是否删除书籍缓存数据
     */
    public void deleteDownBookTask(String userId, String bookId, DeleteListener listener,boolean isDeleteBookData) {
        // 停止下载
        DownloadManager.getInstance().delete(userId, bookId);
        // 删除数据
        if(isDeleteBookData){
            deleteDownBookDate(userId, bookId, listener);
        }
    }

    /**
     * 删除下载任务
     * @param userId
     * @param bookIds
     */
    public void deleteDownBookTasks(String userId, List<String> bookIds){
        deleteDownBookTasks(userId, bookIds, null, false);
    }
    /**
     * 删除下载任务
     * @param userId
     * @param bookIds
     * @param listener 回调在子线程
     * @param isDeleteBookData 是否删除书籍缓存数据
     */
    public void deleteDownBookTasks(String userId, List<String> bookIds, DeleteListener listener,boolean isDeleteBookData) {
        // 全部停止下载
        DownloadManager.getInstance().deleteAll();
        // 删除数据
        if(isDeleteBookData){
            deleteDownBookDates(userId, bookIds,listener);
        }
    }

    /**
     * 获取当前的下载状态
     * @param userId
     * @param bookId
     * @return
     */
    public DownloadInfo getDownBookState(String userId, String bookId) {
        return DownloadManager.getInstance().get(userId, bookId);
    }

    /**
     * 删除一本书的本地下载数据
     * 
     * @param userId
     * @param bookId
     */
    private synchronized void deleteDownBookDate(String userId, String bookId, DeleteListener listener) {
        List<String> list = new ArrayList<String>();
        list.add(bookId);
        deleteDownBookDates(userId, list, listener);
    }

    /**
     * 删除多本书的本地下载数据
     * <B>回调在子线程</B>
     * @param userId
     * @param bookIds
     */
    private synchronized void deleteDownBookDates(final String userId, final List<String> bookIds, final DeleteListener listener) {
        Runnable run =  new Runnable() {
            @Override
            public void run() {
                for (String bookId : bookIds) {
                    try {
                        DownLoadBookUtil.deleteFiles(getShuqiDownBookDataPath(userId, bookId));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if(listener!=null){
                    listener.onFinish();
                }
            }
        };
        MyTask.runInBackground(run, true);
    }
    /**
     * 获取某本书在SD卡上的章节缓存路径
     * @param userId
     * @param bookId
     * @return
     */
    private String getShuqiDownBookDataPath(String userId, String bookId){
        return Config.DEFAULT_SHUQI_CHAPTER_CACHE_PATH + userId + "/" + bookId;
    }



    /** 检查目录是否下载：未下载时，异步下载目录 */
    private synchronized void checkBookCatalog(final String userId, final String bookId,
            final CheckBookCatalogListener listener) {
        long count = BookCataLogDao.getInstance().isDownLoadShuqiBookCatalog(userId, bookId);
        Log4an.i(logTag, "userId=" + userId + " bookId=" + bookId + " , catalog count=" + count);
        if (count > 1) {
            listener.onFinish(true, userId, bookId);
        } else {
            DownLoadListener downLoadListener = new DownLoadListener() {
                public void onLoadSucess(BookData bookData) {
                    listener.onFinish(true, userId, bookId);
                }

                public void onLoadFaild() {
                    listener.onFinish(false, userId, bookId);
                }
            };
            BookCatalogManager.downloadShuQiCatalog(bookId, userId, downLoadListener);
        }
    }

    /** 检查下载地址： */
    private void checkBookDownLoadUrl(String userId, String bookId,
            final CheckBookDownUrlListener urlListener) {
        VerifyBookDownLoadUrlModel model = new VerifyBookDownLoadUrlModel(bookId);
        IEventListener listener = new IEventListener() {
            @Override
            public void onEvent(int event, Object data) {
                Log4an.e(logTag, "checkBookDownLoadUrl  onEvent event=" + event);
                VerifyBookDownUrlInfo info;
                if (event == EventTypeConstants.EVENT_SUCCESS) {
                    info = (VerifyBookDownUrlInfo) data;
                    Log4an.e(logTag, "checkBookDownLoadUrl " + info.toString());
                    if (info != null && !TextUtils.isEmpty(info.getDownLoadUrl())) {
                        urlListener.onFinish(true, info);
                        return;
                    }
                }else if(event == EventTypeConstants.EVENT_EXC_APNNOTEXIST){
                    info = new VerifyBookDownUrlInfo();
                    info.setMessage(getNetError());
                    urlListener.onFinish(false, info);
                }
                info = new VerifyBookDownUrlInfo();
                info.setMessage(getVerifyDownUrlErrorTips());
                urlListener.onFinish(false, info);
            }
        };
        model.addEventListener(listener);
        model.loadData("");
    }
    
    /**
     * 保存书签
     * 
     * @param bookInfo
     * @param uid
     * @param cid
     */
    private boolean saveBookMark(String bookId,String uid, String cid) {
        if(TextUtils.isEmpty(bookId) || TextUtils.isEmpty(uid) || TextUtils.isEmpty(cid)){
            Log4an.e(logTag, "添加书签失败：数据不完整 bookId="+bookId+" uid="+uid+" cid="+cid);
            return false;
        }
        // 判断是否存在书签
        BookMarkInfo markInfo =
                BookMarkInfoDao.getInstance().getBookMark(null, bookId, uid,BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
        BookInfo bookInfo = BookInfoDao.getInstance().getBookInfo("", bookId, uid);
        if ((markInfo == null || markInfo.getDeleteFlag() == BookMarkInfo.FLAG_DELETE)
                && bookInfo != null) {
            markInfo = new BookMarkInfo();
            // 准备书签
            markInfo.setBookId(bookId);
            markInfo.setUserId(uid);
            markInfo.setChapterId(cid);
            if(bookInfo!=null){
                markInfo.setPayMode(bookInfo.getBookPayMode()+"");
            }
            markInfo.setBookType(BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
            markInfo.setTotalChapter(bookInfo.getBookMaxOid() > 0 ? bookInfo.getBookMaxOid() : 0);
            markInfo.setBookCoverImgUrl(bookInfo.getBookCoverImgUrl());
            markInfo.setBookName(bookInfo.getBookName());
            BookMarkInfoDao.getInstance().saveBookMark(markInfo);
            Log4an.i(logTag, "新添加书签成功");
        }else{
            Log4an.e(logTag, "已有书签，未添加书签");
        }
        return true;
    }

    private static interface CheckBookCatalogListener {
        void onFinish(boolean isSuccess, String userId, String bookId);
    }
    private static interface CheckBookDownUrlListener {
        void onFinish(boolean isSuccess, VerifyBookDownUrlInfo info);
    }
    public static interface StartDownBookListener {
        void onFinish(boolean isSuccess, String message);
    }
    
    private String getNetError(){
        return getString(R.string.net_error_text);
    }
    private String getCatalogErrorTips(){
        return getString(R.string.downloadshuqibook_getbookcatalog_error);
    }
    private String getVerifyDownUrlErrorTips(){
        return getString(R.string.downloadshuqibook_verifybookdownloadurl_error);
    }
    private String getString(int resId){
        return ShuqiApplication.getContext().getResources().getString(resId);
    }

}
